import { Channel, UserChannelResponse } from '@/types/data'
import request from '@/utils/request'
import { AppThunk } from '../index'
import { addUserChannel, delUserChannel, setRestChannle, setUserChannle } from '../modules/home'
import _ from 'lodash'

/**
 * 获取用户频道数据：
 * 1. 登录过：获取登录人频道数据
 * 2. 没有登录过：获取默认的频道数据
 * @returns 
 */
export function getUserChannelAction(): AppThunk {
  return async (dispatch, getState) => {
    const res: UserChannelResponse = await request.get('/user/channels')
    console.log('用户频道数据：', res)
    dispatch(setUserChannle(res.data.channels))
  }
}
/**
 * 获取推荐频道
 * @returns 
 */
export function getRestChannleAction(): AppThunk {
  return async (dispatch, getState) => {
    // 1. 获取所有频道数据
    const all: UserChannelResponse = await request.get('/channels')
    console.log('all:', all.data.channels)
    // 2. 获取我的频道数据
    const { userChannel } = getState().home
    // 3. 计算频道推荐 = 所有频道数据 - 我的频道数据   
    dispatch(setRestChannle(_.differenceBy(all.data.channels, userChannel, 'id')))
  }
}
/**
 * 
 * @param channel:{id, name} 当前要删除的频道数据
 * @returns 
 */
export function delChannelAction(channel: Channel): AppThunk {
  return async (dispatch, getState) => {
    // 1. 数据库删除频道
    await request.delete(`/user/channels/${channel.id}`)
    // 2. redux删除
    dispatch(delUserChannel(channel))
  }
}

// 添加我的频道
export const addChannelAction = (channel: Channel): AppThunk => {
  return async (dispatch, getState) => {
    await request.patch('/user/channels', { channels: [channel] })
    // 更新状态
    dispatch(addUserChannel(channel))
  }
}